#include "client_loop.h"

//  ​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​
//  * 主事件循环 - epoll驱动的状态机
//  *   IDLE --发送命令--> AWAIT_RESP --收到响应--> IDLE
//  ​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​*​**​
int run_client_loop(ClientContext *ctx)
{

    // UserLogInfo user;
    // // Command cmd_login_reg;
    // // 显示菜单
    // display_menu(&user, &cmd_login_reg);

    // if(send_command(ctx, cmd_login_reg, &user, sizeof(UserLogInfo)) != 0) {
    //     printf("Send login failed\n");
    //     return -1;
    // }
    // ctx->state = STATE_AWAIT_AUTH;


    int epllfd = epoll_create(1);
    struct epoll_event event;
    // 监控标准输入
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    epoll_ctl(epllfd, EPOLL_CTL_ADD, STDIN_FILENO, &event);

    // 监控套接字
    event.events = EPOLLIN | EPOLLRDHUP;
    event.data.fd = ctx->sockfd;
    epoll_ctl(epllfd, EPOLL_CTL_ADD, ctx->sockfd, &event);

    char input[MAX_BUF_SIZE];        // 输入
    char response_buf[MAX_BUF_SIZE]; // 响应

    printf("Client ready. Enter commands (help for usage):\n");

    struct epoll_event readyset[1024];

    while (1)
    {
        // 阻塞等待事件（无超时）
        int readynum = epoll_wait(epllfd, readyset, 1024, -1);
        // 处理所有就绪事件
        for (int i = 0; i < readynum; i++)
        {
            /* 用户输入事件处理 */
            if (readyset[i].data.fd == STDIN_FILENO)
            {
                if (fgets(input, sizeof(input), stdin) == NULL)
                    continue;

                // 去除换行符
                input[strcspn(input, "\n")] = '\0';

                // 解析用户输入
                ParsedCommand pc;
                int parse_ret = parse_input(input, &pc);

                // 退出命令处理
                if (parse_ret == 1)
                {
                    printf("Goodbye!\n");
                    return 0;
                }
                // 未知命令处理
                else if (parse_ret == -1)
                {
                    printf("Unknown command. Type 'help' for usage.\n");
                    continue;
                }

                // 发送命令到服务器
                if (send_command(ctx, pc.cmd, pc.has_args ? pc.args : NULL,
                                 pc.has_args ? strlen(pc.args) : 0) != 0)
                {
                    printf("Send command failed\n");
                    ctx->state = STATE_ERROR;
                }
                else
                {
                    ctx->state = STATE_AWAIT_RESP; // 状态转移
                }
            }
            /* 服务器响应事件处理 */
            else if (readyset[i].data.fd == ctx->sockfd)
            {
                protocol_header_t header;
                int ret = receive_response(ctx, &header, response_buf,
                                           sizeof(response_buf));
                if (ret != 0)
                {
                    printf("Receive error: %d\n", ret);
                    ctx->state = STATE_ERROR;
                    continue;
                }

                // 根据响应类型分发给不同处理函数
                switch (header.command)
                {
                case CMD_LS_RESP:
                    handle_ls_response(ctx, &header, response_buf);
                    break;
                case CMD_PWD_RESP:
                    handle_pwd_response(ctx, &header, response_buf);
                    break;
                // 其他命令响应...
                default:
                    printf("Unknown response type: %d\n", header.command);
                }
                ctx->state = STATE_IDLE; // 状态转移
            }
        }
    }
    return 0;
}